﻿using System.Security.Cryptography;
using System.Text;

namespace Xwltz.Framework.Tool
{
    public class MachineKeyCreator
    {
        public static string Create(string decryption, int decryptionLength, string validation, int validationLength)
        {

            var decryptionKey = CreateKey(decryptionLength);
            var validationKey = CreateKey(validationLength);

            return @"<machineKey decryption=""" + decryption + @""" decryptionKey=""" + decryptionKey + @",IsolateApps"" validation=""" + validation + @""" validationKey=""" + validationKey + @",IsolateApps""/>";
        }

        private static string CreateKey(int numBytes)
        {
            var rng = new RNGCryptoServiceProvider();
            var buff = new byte[numBytes];

            rng.GetBytes(buff);
            return BytesToHexString(buff);
        }

        private static string BytesToHexString(byte[] bytes)
        {
            var hexString = new StringBuilder(64);

            foreach (var t in bytes)
            {
                hexString.Append($"{t:X2}");
            }
            return hexString.ToString();
        }
    }
}
